package com.example.mqttledmenu;

import android.content.Intent;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.ListFragment;

import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.CircleCrop;
import com.bumptech.glide.load.resource.drawable.DrawableTransitionOptions;
import com.bumptech.glide.request.RequestOptions;
import com.bumptech.glide.request.transition.DrawableCrossFadeFactory;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;

public class FragmentFocus extends ListFragment {

    private ListView lv;
    private SimpleAdapter adapter;
    private View rootView;
    ArrayList<NewsItem> newsList = new ArrayList<>();

    public void getALLNewsList() {
        newsList = new ArrayList<>();
        Retrofit retrofit = new Retrofit.Builder().baseUrl(Config.serverUrl).build();
        UploadService uploadService = retrofit.create(UploadService.class);
        Call<ResponseBody> call = uploadService.getMessage(Config.getInstance().getUserId());
        call.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                String result = null;
                try {
                    result = response.body().string();
                    JsonObject returnData = new JsonParser().parse(result).getAsJsonObject();
                    if (!returnData.get("code").toString().equals("200")) {
                        rootView.findViewById(R.id.isMessageEmpty).setVisibility(View.VISIBLE);
                        return;
                    }
                    try {
                        JSONArray myjsonArray = new JSONArray(returnData.get("data").toString());
                        for (int i = 0; i < myjsonArray.length(); i++) {
                            JSONObject jsonObject = myjsonArray.getJSONObject(i);
                            if (i == 0) Log.d("nightowl", "输出订阅列表：(锚点一)" + jsonObject);
                            newsList.add(new NewsItem(
                                    jsonObject.get("authorAvatar").toString().replace("\"", ""),
                                    (String) jsonObject.get("newsAuthor"),
                                    (String) jsonObject.get("newsDepartment"),
                                    (String) jsonObject.get("newsTitle"),
                                    (String) jsonObject.get("newsContent"),
                                    (String) jsonObject.get("newsPublishTime"),
                                    jsonObject.get("newsId").toString(),
                                    (int) jsonObject.get("isRead")));
                        }
                        adapter = new SimpleAdapter(getActivity(), getData(newsList),
                                R.layout.news_adapter_item, new String[]{"avatar", "publisher", "title", "brief", "time", "read"},
                                new int[]{R.id.avatar, R.id.publisher, R.id.title, R.id.brief, R.id.time, R.id.read});
                        //设置glide占位符
                        RequestOptions requestOptions = new RequestOptions()
                                .placeholder(R.drawable.loading)
                                .error(R.drawable.unknow_person)
                                .fallback(R.drawable.unknow_person);
                        //设置头像切换效果(其实比较耗性能)
                        DrawableCrossFadeFactory factory = new DrawableCrossFadeFactory.Builder().setCrossFadeEnabled(true).build();
                        adapter.setViewBinder(new SimpleAdapter.ViewBinder() {
                            @Override
                            public boolean setViewValue(View view, Object data, String textRepresentation) {
                                if (view.getId() == R.id.avatar) {
                                    ImageView iv = (ImageView) view;
                                    Glide.with(FragmentFocus.this)
                                            .load(data.toString())
                                            .apply(requestOptions)
                                            .transition(DrawableTransitionOptions.with(factory)).transform(new CircleCrop()).into(iv);
                                    return true;
                                }
                                if (view.getId() == R.id.brief) {
                                    TextView tv = (TextView) view;
                                    String str = data.toString();
                                    if (str.length() > 18) {
                                        tv.setText(str.substring(0, 16) + "...");
                                        return true;
                                    }
                                }
                                return false;
                            }
                        });
                        setListAdapter(adapter);
                    } catch (JSONException e) {
                        Log.d("nightowl", "onResponse: yichang");
                        e.printStackTrace();
                    }

                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {

            }
        });
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getALLNewsList();
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        if (rootView == null) {
            rootView = inflater.inflate(R.layout.fragment_focus, container, false);
        }
        initView();
        return rootView;
    }

    //监听点击事件
    @Override
    public void onListItemClick(ListView l, View v, int position, long id) {
        //跳转到详情页,传递news_id参数
        Intent intent = new Intent();
        intent.setClass(getActivity(), DetailsActivity.class);
        Bundle bundle = new Bundle();
        bundle.putString("news_id", newsList.get(position).news_id);
        Log.d("nightowl", "输出页面请求id(锚点一):" + newsList.get(position).news_id);
        bundle.putBoolean("need_read", !newsList.get(position).isRead);
        getALLNewsList();
        intent.putExtras(bundle);
        startActivity(intent);
        super.onListItemClick(l, v, position, id);
    }

    //对数据进行加载
    private List<? extends Map<String, ?>> getData(ArrayList<NewsItem> newsList) {
        List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
        for (NewsItem item : newsList) {
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("avatar", item.avatar);
            map.put("publisher", item.publisher);
            map.put("title", item.title);
            map.put("brief", item.brief);
            map.put("time", item.time);
            map.put("read", item.isRead ? R.drawable.has_read : R.drawable.red_point);
            list.add(map);
        }
        return list;
    }

    private void initView() {
        //处理首页的搜索,对于Fragment只能静态添加点击函数
        lv = rootView.findViewById(android.R.id.list);
    }
}